package com.vincent.common.utils;

import org.apache.log4j.Logger;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 发送邮件工具类
 */
public class SendEmailUtil {
    private static final Logger log=Logger.getLogger(SendEmailUtil.class);
    @Resource
    private JavaMailSenderImpl javaMailSender;

    /**
     * 简单邮件发送
     * @param to 收件人地址
     * @param subject 邮件标题
     * @param text 邮件内容
     */
    @Async
    public void simpleSend(String to, String subject, String text) {
        // 构建简单邮件对象，见名知意
        SimpleMailMessage smm = new SimpleMailMessage();
        // 设定邮件参数
        smm.setFrom(javaMailSender.getUsername());
        smm.setTo(to);
        smm.setSubject(subject);
        smm.setText(text);
        // 发送邮件
        javaMailSender.send(smm);
        log.info("send simple email success");
    }

    /**
     * 发送html邮件
     * @param to 收件人地址
     * @param subject 邮件标题
     * @param text 邮件内容
     * @throws javax.mail.MessagingException
     */
    @Async
    public void richContentSend(String to, String subject, String text) throws MessagingException {
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg, true);
        helper.setFrom(javaMailSender.getUsername());
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text,true);
        javaMailSender.send(msg);
        log.info("send simple email success");
    }

    public JavaMailSenderImpl getJavaMailSender() {
        return javaMailSender;
    }

    public void setJavaMailSender(JavaMailSenderImpl javaMailSender) {
        this.javaMailSender = javaMailSender;
    }
}
